<template>
    <h2>预生产计划添加</h2>
    <el-form ref="ruleFormRef" style="max-width: 600px" :model="form.addDto" :rules="rules" label-width="auto"
        class="demo-ruleForm" :size="formSize" status-icon>
        <table style="width: 100%; border: 1px solid #ccc">
            <tr>
                <td colspan="3" style="background-color: grey">
                    <h3 style="color: aliceblue">基本信息</h3>
                    <hr />
                </td>
            </tr>
            <tr>
                <td>
                    <el-form-item label="单据主题" prop="vendorId">
                        <el-input v-model="form.addDto.ppName" style="width: 300px" />
                    </el-form-item>
                </td>
                <td>
                    <el-form-item label="单据编号" prop="vendorId">
                        <el-input v-model="form.addDto.ppDocuNumber" style="width: 300px" :disabled="true" />
                    </el-form-item>
                </td>
                <td>
                    <el-form-item label="来源单据类型" prop="1">
                        <el-select v-model="form.addDto.ppType" placeholder="请选择" style="width: 300px">
                            <el-option label="无来源" value="0" />
                            <el-option label="新增销售合同" value="1" />
                            <el-option label="新增维修处理" value="2" />
                            <el-option label="新增项目" value="3" />
                        </el-select>
                    </el-form-item>
                </td>
            </tr>
            <tr>
                <td colspan="3">
                    <el-form-item label="备注" prop="desc">
                        <el-input v-model="form.addDto.ppSmark" type="textarea" />
                    </el-form-item>
                </td>
            </tr>
        </table>
        <br />
        <div style="height: 50px;">
            <el-button round @click="addhang()">新增行</el-button>
        </div>

        <!-- 产品表格 -->
        <table border="1" style="border-collapse: collapse; width: 1000px; height: 40px;">
            <thead>
                <tr>
                    <th><input type="checkbox" style="width: 30px;" />
                    </th>
                    <th style="height: 40px;">序号</th>
                    <th>产品名称</th>
                    <th>产品编号</th>
                    <th>规格型号</th>
                    <th>单位</th>
                    <th>本次计划数量</th>
                    <th>交货日期</th>
                    <th>备注</th>
                </tr>
            </thead>
            <tbody>
                <tr v-for="(item, index) in check" :key="index">
                    <td><input type="checkbox" v-model="ids" style="width: 30px;width: 100%;" @click="huoqu" /></td>
                    <td style=" text-align: center;">{{ index + 1 }}</td>
                    <td>
                        <input v-model="item.pName" type="text" placeholder="双击选择产品"
                            style="height: 40px; width: 150px;text-align: center;" @dblclick="dialogVisible = true" />
                    </td>
                    <td>
                        <input v-model="item.pNumber" type="text" style="height: 40px; width: 150px;text-align: center;"
                            @dblclick="dialogVisible = true" :disabled="true" />
                    </td>
                    <td>
                        <input v-model="item.pSpec" type="text" style="height: 40px; width: 150px;text-align: center;"
                            :disabled="true" />
                    </td>
                    <td>
                        <input v-model="item.pUnit" type="text" style="height: 40px; width: 150px;text-align: center;"
                            :disabled="true" />
                    </td>
                    <td>
                        <input v-model="item.pPsNum" type="text" style="height: 40px; width: 150px;text-align: center;"
                            @change="sumRPNum" />
                    </td>
                    <td>
                        <el-date-picker v-model="item.pPsDeliveryDate" type="date" placeholder="请选择"
                            style="height: 40px;width: 150px;text-align: center;" />
                    </td>
                    <td><input v-model="item.pPsSmark" type="text"
                            style="height: 40px;width: 150px;text-align: center;" />
                    </td>
                </tr>
            </tbody>
        </table>
        &nbsp;
        <table border="1" style="border-collapse: collapse; width: 1000px; height: 40px;">
            <tr>
                <td colspan="7">
                    <el-form-item label="数量合计">
                        <el-input v-model="form.sumnum" style="height: 40px; width: 200px;text-align: center;"
                            :disabled="true" />
                    </el-form-item>
                </td>
            </tr>
        </table>
        <!-- 产品名称弹框 -->
        <el-dialog v-model="dialogVisible" title="产品名称选择" width="1000" style="height: 700px;"
            :before-close="handleClose">
            <span></span>
            <template #footer>
                <el-row>
                    <el-col :span="4">
                        <el-tree style="max-width: 600px" :data="VendorType" :props="defaultProps"
                            default-expand-all="true" />
                    </el-col>
                    <el-col :span="20">
                        <el-table :data="productlist" border style="width: 100%"
                            @selection-change="handleSelectionChange">
                            <el-table-column type="selection" width="55" />
                            <el-table-column prop="pName" label="产品名称" align="center" />
                            <el-table-column prop="pNumber" label="产品编号" align="center" />
                            <el-table-column prop="pUnit" label="规格型号" align="center" />
                        </el-table>
                    </el-col>
                </el-row>
                <el-button type="primary" @click="dialogVisible = false">
                    保存
                </el-button>
            </template>
        </el-dialog>
        <el-form-item>
            <el-button type="primary" @click="submitForm(ruleFormRef)">
                保存
            </el-button>
            <el-button @click="resetForm(ruleFormRef)">取消</el-button>
        </el-form-item>
    </el-form>
</template>
<script setup lang="ts">
import { onMounted, ref, reactive, computed } from "vue";
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
const formSize = ref<ComponentSize>("default");
const ruleFormRef = ref<FormInstance>();
const locationOptions = ["Home", "Company", "School"];
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import axios from "axios";
import http from '../../../http.js'
const dialogVisible = ref(false)
const route = useRoute();
const router = useRouter();
const form = reactive({
    preProductionId: '',
    pnames: '',
    pnumber: '',
    pspec: '',
    punit: '',
    pnum: '',
    pdeliverydate: '',
    psmark: '',
    sumnum: 0,
    "addDto": {
        "ppDocuNumber": "",
        "ppName": "",
        "ppNumTotal": '',
        "ppType": '',
        "ppState": '',
        "ppGeneratedNum": '',
        "ppSmark": "",
        "addName": "",
        "office_Id": "",
        "user_Id": '',
        "adddtos": [
            {
                "ppDocuNumber": "",
                "productId": '',
                "pPsNum": '',
                "pPsDeliveryDate": "",
                "pNumber": "",
                "pName": "",
                "pSpec": "",
                "pUnit": "",
                "pPsSmark": ""
            }
        ]
    }
})
//随机数
const generateRandomNumber = () => {
    const a = Math.floor(100000 + Math.random() * 900000); // 生成一个 6 位的随机数
    sessionStorage.setItem('Vendor', JSON.stringify(a));
    form.addDto.ppDocuNumber = String(a);
}
//生命周期函数钩
onMounted(() => {
    generateRandomNumber(); //生成随机数
    ProductList();  //显示产品列表
    getVendorType(); //显示供应商类型
})
const ids = ref([])
//点击新增行
const check = ref([])
const addhang = () => {
    check.value.push({
        pName: '',
        pNumber: "",
        pSpec: "",
        pUnit: "",
        pPsNum: "",
        pPsDeliveryDate: "",
        pPsSmark: "",
        productId: '',
    });
}

//#region  产品名称弹框
//显示供应商中的供应商类别树形
var VendorType = ref([]);
const getVendorType = () => {
    axios.get(http.zblnb + '/cg/api/Vendor/ProductTypeSelect').then(res => {
        if (res.data.code == 0) {
            VendorType.value = res.data.data
        }
        console.log(VendorType.value)
    })
}

const productPage = reactive({
    pindex: 1,
    psize: 100,
    pageLast: 0,
    sumCount: 0,
    PName: "",
    PNumber: "",
})
//显示产品列表
const productlist = ref([])
const ProductList = () => {
    axios.get(http.zblnb + '/cg/api/ProcurementReturn/GetProductList', {
        params: {
            pindex: productPage.pindex,
            psize: productPage.psize,
            PName: productPage.PName || "",
            PNumber: productPage.PNumber || "",
            ProductTypeId: 0
        }
    })
        .then(res => {
            productlist.value = res.data.data.list
            productPage.sumCount = res.data.data.sumCount;
            productPage.pageLast = res.data.data.pageLast
            console.log(res.data)
        })
}

//选中的产品名称
const handleSelectionChange = (val: User[]) => {
    check.value = val
    console.log(val)
    console.log(check.value[0].pName)
}

//#endregion


//点击复选框获取选中的值
const selectedRows = ref([])
const huoqu = () => {
    if (ids.value) {
        selectedRows.value = check.value.filter(item => item.productId);
    }
    console.log(selectedRows.value)
}


//取消
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
    location.reload();
}

//数量合计
//输入数量change事件
const sumRPNum = (sum: number) => {
    form.sumnum += Number(sum.srcElement.__vnode.dirs[0].value);
}

//添加预生产计划
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            var model = {
                ppName: form.addDto.ppName,
                ppDocuNumber: sessionStorage.getItem('Vendor'),
                ppType: form.addDto.ppType,
                ppSmark: form.addDto.ppSmark,
                ppGeneratedNum: '0',
                ppState: '0',
                office_Id: '0',
                user_Id: '0',
                ppNumTotal: String(form.sumnum),
                adddtos: selectedRows.value.map(item => ({
                    ppDocuNumber: item.ppDocuNumber,
                    productId: item.productId,
                    pPsNum: item.pPsNum,
                    pPsDeliveryDate: item.pPsDeliveryDate,
                    pNumber: item.pNumber,
                    pName: item.pName,
                    pSpec: item.pSpec,
                    pUnit: item.pUnit,
                    pPsSmark: item.pPsSmark,
                }))
            }

            console.log(model)
            form.addDto.adddtos = form.addDto.adddtos.filter((item) => item.pPsNum != '')
            axios.post(http.zblnb + '/sc/api/PreProduction/AddPreProduction',{
                addDto: model
            })
                .then(res => {
                    console.log(res.data)
                    if (res.data.data > 0) {
                        ElMessage.success('添加成功');
                        router.push('/ShowPreProduction');
                    }
                    else {
                        ElMessage.error('添加失败');
                    }
                })
        } else {
            console.log('error submit!', fields)
        }
    })
}
</script>
<style>
table {
    width: 100%;
    /* 可选：设置表格宽度 */
    border-collapse: collapse;
    /* 防止单元格之间的间隔 */
}

td {
    text-align: center;
    /* 水平居中 */
    vertical-align: middle;
    /* 垂直居中 */
    border: 1px solid #ddd;
    /* 添加边框用于可视化 */
    padding: 10px;
    /* 单元格内边距 */
}
</style>